<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app"></div>
    <div id="app1"></div>
    <script src="../js/babel.min.js"></script>
    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script type="text/babel">
      class Demo extends React.Component {
        state = {
          opacity: 1,
        };
        death = () => {
          // 清空定时器
          // clearInterval(this.timer);
          // 卸载组件
          ReactDOM.unmountComponentAtNode(document.getElementById("app"));
        };
        active = () => {
          setInterval(() => {
            let { opacity } = this.state;
            opacity -= 0.1;
            if (opacity <= 0) opacity = 1;
            this.setState({ opacity });
          }, 200);
        };
        /**
         * @description 组件渲染完成之后调用，只调用一次
         */
        componentDidMount() {
          this.timer = setInterval(() => {
            let { opacity } = this.state;
            opacity -= 0.1;
            if (opacity <= 0) opacity = 1;
            this.setState({ opacity });
          }, 200);
        }
        /**
         * @description 组件将要被卸载时调用
         */
        componentWillUnmount() {
          clearInterval(this.timer);
        }
        render() {
          // setInterval(() => {
          //   let { opacity } = this.state;
          //   opacity -= 0.1;
          //   if (opacity <= 0) opacity = 1;
          //   this.setState({ opacity });
          // }, 200);
          console.log("render");
          return (
            <div>
              <h3 style={{ opacity: this.state.opacity }}>this is text</h3>
              <button onClick={this.death}>销毁组件</button>
              <button onClick={this.active}>开始变化</button>
            </div>
          );
        }
      }
      ReactDOM.render(<Demo />, document.getElementById("app"));
    </script>
  </body>
</html>
